<template>
  <div class="ebook" ref="ebook">
    <EbookHeader></EbookHeader>
    <EbookReader></EbookReader>
    <EbookTitle></EbookTitle>
    <EbookMenu></EbookMenu>
    <EbookBookMark></EbookBookMark>
    <EbookFooter></EbookFooter>
  </div>
</template>

<script>
import EbookReader from '@/components/ebook/EbookReader.vue';
import EbookTitle from '@/components/ebook/EbookTitle.vue';
import EbookMenu from '@/components/ebook/EbookMenu.vue';
import EbookBookMark from '@/components/ebook/EbookBookMark.vue';
import EbookHeader from '@/components/ebook/EbookHeader.vue';
import EbookFooter from '@/components/ebook/EbookFooter.vue';

import { getReadTime, saveReadTime } from '@/utils/localStorage';
import { ebookMixin } from '@/utils/mixin';

export default {
  mixins: [ebookMixin],
  components: {
    EbookHeader,
    EbookReader,
    EbookTitle,
    EbookMenu,
    EbookBookMark,
    EbookFooter,
  },
  watch: {
    offsetY(newValue) {
      // !下面这个注释是正确的
      if (!this.menuVisible && this.bookAvailable) {
        if (newValue > 0) {
          this.move(newValue);
        } else if (newValue === 0) {
          this.restore();
        }
      }

      // if (newValue > 0) {
      //   this.move(newValue);
      // } else if (newValue === 0) {
      //   this.restore();
      // }
    },
  },
  methods: {
    // *记录用户阅读时长
    startLoopReadTime() {
      let readTime = getReadTime(this.fileName);
      if (!readTime) {
        readTime = 0;
      }
      this.task = setInterval(() => {
        readTime++;
        if (readTime % 30 === 0) {
          saveReadTime(this.fileName, readTime);
        }
      }, 1000);
    },
    // *Y偏移函数
    move(newValue) {
      this.$refs.ebook.style.top = newValue + 'px';
    },
    // *还原位置函数
    restore() {
      this.$refs.ebook.style.top = 0;
      this.$refs.ebook.style.transition = 'all 0.2s linear';
      setTimeout(() => {
        this.$refs.ebook.style.transition = '';
      }, 200);
    },
  },
  mounted() {
    this.startLoopReadTime();
  },
  beforeDestroy() {
    if (this.task) clearInterval(this.task);
  },
};
</script>

<style lang="scss" scoped>
@import '../../assets/styles/global';
.ebook {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
</style>
